﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServeNHL.Models;


namespace ServeNHL.Controllers
{
    
    public class EventsController : Controller
    {
        // GET: Events
        public ActionResult Index()
        { //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            var events = new eventViewModel();
            var eventList = new List<eventViewModel>();

            eventList = events.getUpcomingEvents();
            return View(eventList);
        }

        public ActionResult Portal()
        {
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            var events = new eventViewModel();
            var eventList = new List<eventViewModel>();

            eventList = events.getUpcomingEvents();
            return View(eventList);
        }


        public ActionResult EventItem()
        {
            var events = new eventViewModel();
            int eventID; 

            if (!Int32.TryParse(Request["EventId"], out eventID))
            {
                eventID = 0;
            }

            events = events.getEvent(eventID);
            return View(events);
        }

        public ActionResult View(int id)
        {
            var events = new eventViewModel();
            events = events.getEvent(id);
            return View(events);
        }

        public ActionResult Add()
        {
            return View("Form");
        }

        public ActionResult Edit(int id)
        {
            var events = new eventViewModel();
            events = events.getEvent(id);
            return View("Form", events);
        }
        //disassociates a user from an event
        public ActionResult DeleteSignup (int id)
        {
            int userid = Convert.ToInt32(Session["userid"]);
            EVENT_SIGNUP es = new EVENT_SIGNUP();
            using (var db = new fclick_dbEntities())
            {
                var q = db.EVENT_SIGNUP.Where(u => u.USER_ID == userid && u.EVENT_ID == id).FirstOrDefault();
                db.EVENT_SIGNUP.Remove(q);
                db.SaveChanges();
            }

            return RedirectToAction("UserEvents", "Events");
        }

        //insert into event signup | associates a user with an event
        public ActionResult Signup(int id)
        {
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            //Query to check if signed up

            string userid = Session["userid"].ToString();

            if (!alreadySignedUp(id, Convert.ToInt32(userid)))
            {
                EVENT_SIGNUP es = new EVENT_SIGNUP();
                es.USER_ID = Convert.ToInt32(userid);
                es.EVENT_ID = id;
                //es.GUEST_FLAG = Request["Guestflag"]; placeholder until created
                //es.NUM_GUESTS= Request["numGuests"];
                es.STATUS = "Active";

                es.InsertEventSignUp(es);
                //viewbag message?
                ViewBag.Message = "You are signed up";
            }
            else
            {
                ViewBag.Message = "You are already signed up for this event.";
            }

            return RedirectToAction("UserEvents");
        }

        /// <summary>
        /// Checks if a user is already signed up for an event.
        /// </summary>
        /// <param name="EventID">ID of the event</param>
        /// <param name="UserID">ID of the user</param>
        /// <returns>True if the user is already signed up for an event.</returns>
        public Boolean alreadySignedUp(int EventID, int UserID)
        {
            using (var dbconn = new fclick_dbEntities())
            {
                var query = (from es in dbconn.EVENT_SIGNUP
                             where es.EVENT_ID == EventID
                             where es.USER_ID == UserID
                             select es).Count();

                if (query > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
        } // End of public Boolean alreadySignedUp(int EventID, int UserID)

        [HttpPost]
        public ActionResult SaveEvent()
        {
            var eventItem = new EVENT();
            int eventID = 0;

            eventItem.NAME = Request["eventName"];
            eventItem.EVENT_CAT_ID = Int32.Parse(Request["eventCategory"]);
            eventItem.EVENT_DESC = Request["eventDescription"];
            eventItem.OWNER_ID = Convert.ToInt32(Session["userid"].ToString());
            eventItem.START_DATE = DateTime.Parse(Request["eventStartDate"]);
            eventItem.END_DATE = DateTime.Parse(Request["eventEndDate"]);
            eventItem.STATUS = "Active";
            eventItem.NUM_GUESTS = 0;
            eventItem.MIN_PARTICIPANTS = Int32.Parse(Request["eventMinParticipants"]);
            eventItem.MAX_PARTICIPANTS = Int32.Parse(Request["eventMaxParticipants"]);
            eventItem.NEED_FLAG = (Request["eventIsNeed"] == "1");
            eventItem.VCL_ID = Int32.Parse(Request["eventVLC"]);

            eventID = eventItem.SaveEvent(eventItem);

            return RedirectToAction("Index", "Events");
        }

        public ActionResult Dashboard()
        {
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            var eventItem = new eventViewModel();
            var eventList = new List<eventViewModel>();

            eventList = eventItem.getUpcomingEvents();

            return View(eventList);
        }

        /**************************************************
         * Event Category Controls
         *************************************************/
        public ActionResult CategoryDashboard()
        {
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            var cat = new EVENT_CAT();
            var category = new List<EVENT_CAT>();

            category = cat.getAllCategories();

            return View("CategoryDashboard", category);
        }

        public ActionResult AddCategory()
        {
            var category = new EVENT_CAT();
            return View("CategoryForm", category);
        }

        public ActionResult EditCategory()
        {
            var category = new EVENT_CAT();
            return View("CategoryForm", category);
        }

        public ActionResult SaveCategory()
        {
            var category = new EVENT_CAT();
            category.EVENT_CAT_NAME = Request["name"];
            category.EVENT_CAT_DESC = Request["description"];
            category.STATUS = Request["status"];
            category.VCL_ID = (String.IsNullOrEmpty(Request["vclList"])) ? 0 : Int32.Parse(Request["vclList"]);

            var vm = new eventViewModel();
            vm.eventCat = category;

            var id = category.saveEventCat(vm.eventCat);
            return View("CategoryDashboard");
        }

        /**************************************************
         * Event Volunteer Control List Controls
         *************************************************/
        public ActionResult VCLDashboard()
        {
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            var vcl = new VCLViewModel();
            var vclList = new List<VCLViewModel>();
            vclList = vcl.getVCLs();

            return View("VCLDashboard", vclList);
        }       // end of public ActionResult VCLDashboard()

        public ActionResult AddVCL()
        {
            var vcl = new VCLViewModel();
            vcl.VCL = new VOLUNTEER_CONTROL_LIST();
            vcl.VCLMembers = new List<VCL_MEMBERS>();
            return View("VCLForm", vcl);
        }       // end of public ActionResult VCLDashboard()

        public ActionResult EditVCL()
        {
            var vcl = new VCLViewModel();
            return View("VCLForm", vcl);
        }       // end of public ActionResult VCLDashboard()

        public ActionResult SaveVCL()
        {
            var vcl = new VCLViewModel();
            vcl.VCL = new VOLUNTEER_CONTROL_LIST();
            vcl.VCLMembers = new List<VCL_MEMBERS>();

            vcl.VCL.LIST_DESC = Request["list_desc"];
            vcl.VCL.STATUS = Request["status"];

            var requestVars = Request.ServerVariables;
            var keys = requestVars.AllKeys;

            for (int i = 0; i < keys.Length; i++)
            {
                var requestVar = requestVars.GetValues(keys[i]);
                if (requestVars[i].Contains("memberList_"))
                {
                    var varArray = requestVars[i].Split('_');
                    var member = new VCL_MEMBERS();
                    member.STATUS = "Active";
                    member.USER_ID = Int32.Parse(varArray[2]);
                    //for (int j = 0; j < requestVar.Length; j++)
                    //{

                    //    Response.Write("Value " + j + ": " + Server.HtmlEncode(requestVar[j]) + "<br>");
                    //}
                }
            }

            vcl.saveVCLList(vcl);

            return View("VCLDashboard");
        }
        //for Userevents page
        public ActionResult UserEvents()
        {
            //redirect to login if not signed in
            if (Session["userid"] == null)
            {
                ViewBag.Message = "Please sign in";
                return RedirectToAction("login", "Security", new { msg = "Please login to continue" });
            }
            int userid =  Convert.ToInt32(Session["userid"]);
            var eventItem = new eventViewModel();
            var eventList = new List<eventViewModel>();

           
            eventList = eventItem.userEvents(userid);
            return View(eventList);
        }
    }       // end of  public class EventsController : Controller

   

}
